from smart_cutter.method import *


class SocketTranslateFile(object):
    def __init__(self, host, port, recv_buffer, file_path):
        self.host = host
        self.port = port
        self.recv_buffer = recv_buffer
        self.file_path = file_path
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((self.host, self.port))
        except:
            raise Exception("連接機台失敗！")

    def adjust(self):

        with open(self.file_path, 'rb') as f:
            file_context = f.read()
            file_context_aa = file_context.decode("ISO-8859-1")
            crc_code = crcFast(file_context_aa, len(file_context_aa))
            crc_code = int(crc_code, 16)
        file_size = os.path.getsize(self.file_path)
        message_1 = "file_info" + str(file_size) + ' ' + str(crc_code)
        self.sock.send(message_1.encode())
        ready_info = self.sock.recv(50)
        if ready_info.decode('utf-8') == "translate_ready":
            translate_file = open(self.file_path, 'rb')
            while True:
                file_data = translate_file.read(self.recv_buffer)
                self.sock.send(file_data)
                if not file_data:
                    break
            translate_file.close()

            finish_info1 = self.sock.recv(50)
            finish_info2 = self.sock.recv(50)
            finish_info2 = finish_info2.decode("utf-8")
        else:
            raise Exception("幾台沒有反應！")

        return finish_info2
